/**
 * Created by Administrator on 2018/7/29.
 */
class utils{



    /**
     * 根据name关键字创建一个Bitmap对象
     */
    public static createBitmapByName(name: string,config:any = null):TbitMap {
        let result = new TbitMap();
        result.texture = RES.getRes(name);

        if(config != null){
            if(config.hasOwnProperty('scaleX')){
                result.scaleX = config.scaleX;
            }
            if(config.hasOwnProperty('scaleY')){
                result.scaleY = config.scaleY;
            }
            if(config.hasOwnProperty('alpha')){
                result.alpha = config.alpha;
            }
            if(config.hasOwnProperty('width')){
                result.width = config.width;
                result.height = config.width * result.texture.textureHeight / result.texture.textureWidth;
            }
            if(config.hasOwnProperty('offsetX')){
                result.anchorOffsetX = result.width * config.offsetX;
            }
            if(config.hasOwnProperty('offsetY')){
                result.anchorOffsetY = result.height * config.offsetY;
            }
        }

        return result;
    }

    // 时间戳转 时分秒
    public static timerSecondFormat(intDiff) {
		var minute = 0, second = 0, hour = 0;
		var mm = '', ss = '', hh = '';
		if (intDiff > 0) {
			minute = Math.floor((intDiff % 3600) / 60);
			second = Math.floor(intDiff % 60);
			hour = Math.floor(intDiff / 3600);
		}
		if (hour > 999)
			hour = 999;
		hh = hour.toString();
		if (hour <= 9) {
			hh = '0' + hour;
		} else {
			hh = "" + hour;
		}
		if (minute <= 9) {
			mm = '0' + minute;
		} else {
			mm = '' + minute;
		}
		if (second <= 9) {
			ss = '0' + second;
		} else {
			ss = '' + second;
		}
		return hh + ':' + mm + ':' + ss;
	}

    public static createSprite(config:any = null):egret.Sprite{
        let sprite:egret.Sprite = new egret.Sprite();
        if(config != null){
            if (config.hasOwnProperty("width") && typeof config.width == 'number'){
                sprite.width = config.width;
            }
            if (config.hasOwnProperty("height") && typeof config.width == 'number'){
                sprite.height = config.height;
            }
            if (config.hasOwnProperty("offsetX") && typeof config.offsetX == 'number'){
                sprite.anchorOffsetX = config.width * config.offsetX;
            }
            if (config.hasOwnProperty("offsetY") && typeof config.offsetY == 'number'){
                sprite.anchorOffsetY = config.height * config.offsetY;
            }
            if (config.hasOwnProperty("x") && typeof config.width == 'number'){
                sprite.x = config.x;
            }
            if (config.hasOwnProperty("y") && typeof config.width == 'number'){
                sprite.y = config.y;
            }
        }
        return sprite;
    }

    private static TEXT_CONFIG:any = {
        size:26,
        textColor:0x000000,
        textAlign:egret.HorizontalAlign.CENTER,
        verticalAlign:egret.VerticalAlign.MIDDLE,
        bold:false,
        stroke:0,
        fontFamily:'微软雅黑',
    };
    public static createTextField(config:any={}):egret.TextField{
        let textField:egret.TextField = new egret.TextField();
        //混合
        for(let k in this.TEXT_CONFIG){
            if(!config.hasOwnProperty(k)){
                config[k] = this.TEXT_CONFIG[k];
            }
        }
        for (let key in config){
            if(config[key] != null){
                textField[key] = config[key];
            }
        }
        return textField;
    }
   




    /**
     * 获取指定格式时间
     * @param format
     * @param time
     * @returns {string}
     */
    public static getFormateDate(format:string,time:number = null):string{
        var date = new Date();
        if(time != null){
            date.setTime(time * 1000);
        }
        var o = {
            "M+" : date.getMonth()+1, //month
            "d+" : date.getDate(), //day
            "h+" : date.getHours(), //hour
            "m+" : date.getMinutes(), //minute
            "s+" : date.getSeconds(), //second
        };
        if(/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        for(var k in o) {
            if(new RegExp("("+ k +")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
            }
        }
        return format;
    }


    public static getRandomColor():number{
        return GameData.colorArray[Math.floor(Math.random()*GameData.colorArray.length)];
    }

    // 获取视图对象最大x
    public static getMaxX(obj:egret.DisplayObject){
        return obj.x + obj.width - obj.anchorOffsetX;
    }

    // 获取视图对象最大y
    public static getMaxY(obj:egret.DisplayObject){
        return obj.y + obj.height - obj.anchorOffsetY;
    }
        // 超出部分用省略号代替
    public static getChar(_str: string, _len: number,_is?:boolean): string {
        if(!_str) return;
        var _ba: egret.ByteArray = new egret.ByteArray;

        _ba.writeUTFBytes(_str);
        if (_ba.length <= _len) return _str;

        _ba.position = 0;

        if(_is==null || !_is){
            return _ba.readUTFBytes(_len) + "...";
        }else{
            return _ba.readUTFBytes(_len);
        }
    }
    
    /**
         * @language zh_CN
         * 画一个圆角矩形，可以带边框,可以分别控制四个角的圆角大小
         * @param x 矩形的x坐标
         * @param y 矩形的y坐标
         * @param width 矩形的宽
         * @param height 矩形的高
         * @param backgroundColor 矩形的背景颜色
         * @param radio1 左上角的圆角半径
         * @param radio2 右上角的圆角半径 （默认取radio1的值）
         * @param radio3 右下角的圆角半径  （默认取radio1的值）
         * @param radio4 左下角的圆角半径（默认取radio1的值）
         * @param borderColor 边框颜色  
         * @param borderColor 边框宽度
         * @version Egret 2.4
         * @platform Web,Native
         */
    static drawRound(x: number, y: number, width: number, height: number, backgroundColor: number, radio1: number, borderWidth?: number, borderColor?: number, radio2?: number, radio3?: number, radio4?: number, backgroundColorAlpha?: number, obj?: egret.Shape) {
        var shap = obj ? obj : new egret.Shape;
        shap.graphics.clear();
        if (radio2 == null) {
            radio2 = radio1;
        }

        if (radio3 == null) {
            radio3 = radio1;
        }

        if (radio4 == null) {
            radio4 = radio1;
        }
        if (backgroundColorAlpha == null) {
            backgroundColorAlpha = 1;
        }
        let radioCenter1: egret.Point = new egret.Point(x + radio1, radio1 + y);
        let radioCenter2: egret.Point = new egret.Point(x + width - radio2, radio2 + y);
        let radioCenter3: egret.Point = new egret.Point(x + width - radio3, y + height - radio3);
        let radioCenter4: egret.Point = new egret.Point(x + radio4, y + height - radio4);
        let startPoint: egret.Point = new egret.Point(radioCenter1.x, y);
        shap.graphics.beginFill(backgroundColor, backgroundColorAlpha);
        shap.graphics.moveTo(startPoint.x, startPoint.y);
        shap.graphics.lineTo(radioCenter2.x, y);
        shap.graphics.drawArc(radioCenter2.x, radioCenter2.y, radio2, - Math.PI / 2, 0, false);
        shap.graphics.lineTo(x + width, radioCenter3.y);
        shap.graphics.drawArc(radioCenter3.x, radioCenter3.y, radio3, 0, Math.PI / 2, false);
        shap.graphics.lineTo(radioCenter4.x, y + height);
        shap.graphics.drawArc(radioCenter4.x, radioCenter4.y, radio4, Math.PI / 2, Math.PI, false);
        shap.graphics.lineTo(x, radioCenter1.y);
        shap.graphics.drawArc(radioCenter1.x, radioCenter1.y, radio1, Math.PI, -Math.PI / 2.0, false);
        shap.graphics.endFill();


        // 画边框
        if (borderWidth != null || borderColor != null) {
            // 说明设置了边框，花边框
            borderColor = null ? 0x000000 : borderColor;
            borderWidth = null ? 1 : borderWidth
            shap.graphics.lineStyle(borderWidth, borderColor);
            shap.graphics.moveTo(startPoint.x, startPoint.y);
            // currentPoint.setTo(x + width - radio2, y);
            shap.graphics.lineTo(radioCenter2.x, y);
            shap.graphics.drawArc(radioCenter2.x, radioCenter2.y, radio2, - Math.PI / 2, 0, false);
            shap.graphics.lineTo(x + width, radioCenter3.y);
            shap.graphics.drawArc(radioCenter3.x, radioCenter3.y, radio3, 0, Math.PI / 2, false);
            shap.graphics.lineTo(radioCenter4.x, y + height);
            shap.graphics.drawArc(radioCenter4.x, radioCenter4.y, radio4, Math.PI / 2, Math.PI, false);
            shap.graphics.lineTo(x, radioCenter1.y);
            shap.graphics.drawArc(radioCenter1.x, radioCenter1.y, radio1, Math.PI, -Math.PI / 2.0, false);
            shap.graphics.endFill();
        }
        return shap;
    }

    public static getCookie(c_name) {
        var strCookie = document.cookie;
        var arrCookie = strCookie.split(";");
        for (var i = 0; i < arrCookie.length; i++) {
            var arr = arrCookie[i].split("=");
            if (c_name == arr[0].replace(/(^\s*)|(\s*$)/g, "")) {
                return arr[1];
            }
        }
        return "";
        // <begin>
        // wx.getStorageSync(c_name);
        // </begin>
    }

    public static getAllCookie() {
        return document.cookie;
    }
    public static setCookie(c_name, value) {
        // var exdate = new Date()
        // exdate.setDate(exdate.getDate() + expiredays)
        document.cookie = c_name + "=" + value;
        // <begin>
        // wx.setStorageSync(c_name, value);
        // </begin>
    }
    public static getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null)
            return decodeURI(r[2]);
        return null;
    }


    public static getSignStr(params, signKey) {
        var keys = Object.keys(params).sort();
        var signStr_sort = '';
        for (var i = 0, n = keys.length, key; i < n; i++) {
            key = keys[i];
            signStr_sort += key + '=' + params[key] + '&';
        };
        signStr_sort += ('key=' + signKey);
        return signStr_sort;
    }

    /*
     * md5获取签名
     */
    public static getSign(params, signKey) {
        delete params.sign;
        return new md5().hex_md5(utils.getSignStr(params, signKey));
    }


    public static checkResult(r1,r2){

        var res = 'Anti Tracks is a complete solution to protect your privacy and enhance yourcks securely information storomputer Anti  Explorer AOL Netscape Mozilla and Opera browsers It also include more';

        return new Promise((reslove,reject)=>{
            /*加密接口*/
            var time = Math.floor(new Date().getTime());
            var p = {
                tvmid:utils.getCookie('tvmid'),
                rf:r1,
                rs:r2,
                sign_time:time
            };
            var sign_str = utils.getSign(p,Key.k1(res));
            var params = {
                tvmid:utils.getCookie('tvmid'),
                rf:r1,
                rs:r2,
                sign:sign_str,
                sign_time:time
            };
            var x_str = XXTEA.encryptToBase64(JSON.stringify(params), Key.k2(res));
            x_str = x_str.replace(/\+/g,'%2B');
            CurlUtil.curl(config.api_url+'/bxg/add_score',{
                data:x_str,
                tvmid:utils.getCookie('tvmid'),
                apptoken:utils.getCookie('apptoken')
            }).then((data:any)=>{
                if(data.code == 200){
                    let score = data.data.score;
                    let isBaoji = false;
                    if(score >= GameData.maxScore * 0.9){
                        isBaoji = true;
                    }else{
                        isBaoji = false;
                    }
                    var result = {
                        code:data.code,
                        score:score,
                        b:isBaoji
                    }
                    reslove(result);
                }else{
                    reject(data);
                }
            }).catch(function () {
                reject();
            });
        });
    }

    public static checkGuestResult(r1,r2){

        var res = 'Anti Tracks is a complete solution to protect your privacy and enhance yourcks securely information storomputer Anti  Explorer AOL Netscape Mozilla and Opera browsers It also include more';

        return new Promise((reslove,reject)=>{
            /*加密接口*/
            var time = Math.floor(new Date().getTime());
            var p = {
                rf:r1,
                rs:r2,
                sign_time:time
            };
            var sign_str = utils.getSign(p,Key.k1(res));
            var params = {
                rf:r1,
                rs:r2,
                sign:sign_str,
                sign_time:time
            };
            var x_str = XXTEA.encryptToBase64(JSON.stringify(params), Key.k2(res));
            x_str = x_str.replace(/\+/g,'%2B');
            CurlUtil.curl(config.api_url+'/bxg/guest_addscore',{
                data:x_str,
                pre_apptoken:utils.getCookie('apptoken')
            }).then((data:any)=>{
                if(data.code == 200){
                    let score = data.data.score;
                    let isBaoji = false;
                    if(score >= GameData.maxScore * 0.9){
                        isBaoji = true;
                    }else{
                        isBaoji = false;
                    }
                    var result = {
                        code:data.code,
                        score:score,
                        b:isBaoji
                    }
                    reslove(result);
                }else{
                    reject(data);
                }
            }).catch(function () {
                reject();
            });
        });
    }

}